package site.wanjiahao.handler.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import site.wanjiahao.message.request.RpcRequestMessage;
import site.wanjiahao.message.response.RpcResponseMessage;
import site.wanjiahao.util.ConfigPropertiesHolder;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@ChannelHandler.Sharable
public class RpcRequestMessageHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage msg) {
        // 根据接口获取对应的实现类，可以使用Spring，直接在IOC容器中获取
        // 在此使用promise大特错特，2java
//            Promise<Object> promise = ProxyFactory.getPromise(msg.getSequenceId());
        RpcResponseMessage rpcResponseMessage = new RpcResponseMessage();
        rpcResponseMessage.setRequestId(msg.getSequenceId());
        try {
            Class<?> interfaceClazz = msg.getInterfaceClazz();
            Class<?> implClazz = ConfigPropertiesHolder.getImpl(interfaceClazz);
            Object o = implClazz.newInstance();
            Method method = implClazz.getDeclaredMethod(msg.getMethodName(), msg.getParamsTypes());
            Object invoke = method.invoke(o, msg.getParameterValue());
            rpcResponseMessage.setResult(invoke);
        } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
            rpcResponseMessage.setSuccess(false);
            rpcResponseMessage.setReason(e.getCause().toString());
        }
        ctx.writeAndFlush(rpcResponseMessage);
    }
}
